<template>
  <div class="u-editor">
    <div class="toolbar">
      <div
        class="tool-item"
        :class="{ active: command === 'created' }"
        @click="onCommand('created')"
      >
        <span class="iconfont icon-chuangjian"></span>
      </div>
      <div
        class="tool-item"
        :class="{ active: command === 'origin' }"
        @click="onCommand('origin')"
      >
        <span class="iconfont icon-region"></span>
      </div>

      <div
        class="tool-item"
        :class="{ active: command === 'select' }"
        @click="onCommand('select')"
      >
        <span class="iconfont icon-pointer"></span>
      </div>
      <div
        class="tool-item"
        :class="{ active: command === 'create' }"
        @click="onCommand('create')"
      >
        <span class="iconfont icon-rectangle"></span>
      </div>
      <div
        class="tool-item"
        :class="{ active: command === 'daochu' }"
        @click="onCommand('daochu')"
      >
        <span class="iconfont icon-daochu"></span>
      </div>
    </div>
    <div class="rect-bar"></div>
    <div class="img-panel">
      <div class="panel-left">
        <div class="menu active">
          <span class="iconfont icon-listview"></span>
        </div>
        <!-- <div class="menu">
          <span class="iconfont icon-pointer"></span>
        </div> -->
      </div>
      <div class="panel-right">
        <div class="panel-header">
          <div style="flex-grow: 1">
            <el-input size="small" v-model="search" placeholder="查询" />
          </div>
          <div>
            <span class="iconfont icon-daoru" @click.stop="onNodeImport"></span>
            <span class="iconfont icon-delete"></span>
          </div>
        </div>
        <div class="panel-right-warpped">
          <div
            class="list-item"
            v-for="item in nodeList"
            :key="item.uid"
            @click="selectedNode(item)"
          >
            <!-- <el-checkbox
              
            /> -->
            <el-image
              style="width: 30px; height: 30px; margin-left: 10px"
              :src="item.src"
              fit="scale-down"
            />
            <div class="item-right">
              <span>{{ item.name }}</span>
            </div>
            <div class="item-opt" @click.stop="deleteItem(item)">
              <span class="iconfont icon-delete"></span>
            </div>
          </div>
          <div class="list-item" style="height:40px"></div>
        </div>
      </div>
    </div>

    <div class="prop-panel">
      <el-form
        label-width="100px"
        :model="currentRect"
        style="max-width: 460px"
      >
        <el-form-item label="key">
          <el-input
            v-model="rectAttr.name"
            size="small"
            @input="onCancelRect"
          />
        </el-form-item>
        <el-form-item label="x">
          <el-input v-model="rectAttr.x" size="small" @input="onCancelRect" />
        </el-form-item>
        <el-form-item label="y">
          <el-input v-model="rectAttr.y" size="small" @input="onCancelRect" />
        </el-form-item>
        <el-form-item label="w">
          <el-input v-model="rectAttr.w" size="small" @input="onCancelRect" />
        </el-form-item>
        <el-form-item label="h">
          <el-input v-model="rectAttr.h" size="small" @input="onCancelRect" />
        </el-form-item>
      </el-form>
    </div>
    <div class="canvas-content" id="ccanvas"></div>
  </div>
</template>

<script>
import { CreateCanvas } from "./CreateCanvas";
import BgRender from "./BgRender";
import Rect from "./js/obj/Rect";
import TextTure from "./js/obj/TextTure";
import { readFile, dataURL2Image } from "../../utils";
import { PlistReader } from "../../utils/PlistReader";
import apis from "../../apis/index";

const graph = apis.getModuleApis("graph");
export default {
  data() {
    return {
      projectId: '',
      command: "",
      search: "",
      nodeList: [],
      rectAttr: { uid: "", name: "", w: 0, h: 0, x: 0, y: 0 },
    };
  },
  computed: {},
  mounted() {


    let {query} = this.$route
  
    if(query.id){
      this.projectId = query.id
    }

    this.cc = new CreateCanvas({ el: "ccanvas" });
    this.cc.appendRender("background", new BgRender());

    this.cc.selectNode = ({ node, checkedRects }) => {
      this.setRectAttr(node);
    };
    this.cc.createNode = this.createNode;
    this.cc.nodeMove = ({ event, pos }) => {
      let currentNode = this.cc.datas.UIslectNode.selected;
      let idx = this.nodeList.findIndex((v) => v.uid === currentNode.uid);
      if (idx !== -1) {
        let newObj = currentNode.toObj();

        if (this.bgData) {
          let data = this.bgData.getTexureData(currentNode.transform);
          newObj.src = data;
        }
        this.setRectAttr(newObj);
        this.saveNodeRo(newObj);
        this.nodeList.splice(idx, 1, newObj);
      }
    };
    this.cc.created = () => {
      // let imgdatas = localStorage.getItem("img-datas");
      // imgdatas = JSON.parse(imgdatas);

      return new Promise(async (resolve, reject) => {
        graph.getProject(this.projectId).then(async (res) => {
          let image = res.data.data.image;
          let list = res.data.data.list;

          await this.oncreated({
            data: image.src,
            fileName: image.fileName,
          });

          list.forEach((v) => {
            v.order = v.sort;
            let rect = this.createNode(
              v,
              {
                w: v.transform.w,
                h: v.transform.h,
              },
              false
            );
            this.cc.datas.renderDatas.push(rect);
          });

          resolve(true);
        });
  
      });
    };
    this.cc.init();
  },
  methods: {
    createNode(obj, box = { w: 24, h: 24 }, upd = true) {
      let rect = new Rect({
        ...obj,
        name: obj.name || "node_" + this.nodeList.length,
        transform: {
          ...obj.transform,
          ...box,
        },
        property: { lineWidth: 1, color: "#ff00ff" },
      });

      let oo = rect.toObj();

      if (this.bgData) {
        let data = this.bgData.getTexureData(rect.transform);
        oo.src = data;
      }
      if (upd) {
        this.saveNodeRo(oo);
      }

      this.nodeList.push(oo);
      // console.log(this.nodeList);
      return rect;
    },
    saveNodeRo(obj) {
      graph
        .saveProject({
          ...obj,
          src: "",
          projectId: this.projectId,
          type: "rect",
        })
        .then((res) => {
          let idx = this.nodeList.findIndex((node) => node.uid === obj.uid);

          if (idx !== -1) {
            this.nodeList[idx].id = res.data.data;
          }
          let rect = this.cc.datas.renderDatas.find(
            (node) => node.uid === obj.uid
          );
          if (rect) {
            rect.id = res.data.data;
          }
        });
    },
    deleteItem(item) {
      let idx = this.nodeList.findIndex((node) => node.uid === item.uid);

      if (idx !== -1) {
        this.nodeList.splice(idx, 1);
      }
      idx = this.cc.datas.renderDatas.findIndex(
        (node) => node.uid === item.uid
      );
      if (idx !== -1) {
        if (item.uid === this.cc.datas.UIslectNode.selected.uid) {
          this.cc.datas.UIslectNode.selected.hideUISelect();
        }
        this.cc.datas.renderDatas.splice(idx, 1);

        this.cc.RenderManager.render("base");
        graph.deleteContext(item.id);
      }
    },
    async onNodeImport() {
      let result = await readFile("text");
      this.plistText = result.data;
      let reader = PlistReader.reader2Text(result.data).toPlistRes();

      this.fileName = reader.metadata.textureFileName;

      reader.list.forEach((v) => {
        let node = new Rect({
          name: v.key.split(".")[0],
          transform: { ...v.frame },
          property: { lineWidth: 1, color: "#ff00ff" },
        });

        let oo = node.toObj();
        if (this.bgData) {
          let data = this.bgData.getTexureData(oo.transform);
          oo.src = data;
        }
        this.nodeList.push(oo);
        this.cc.datas.renderDatas.push(node);
        this.cc.RenderManager.renderAll(["grid"]);
      });
    },
    selectedNode(item) {
      this.onCommand("select");
      let node = this.cc.datas.renderDatas.find(
        (node) => node.uid === item.uid
      );

      if (node) {
        node.hideUISelect();
        node.showUISelect();
        this.cc.RenderManager.render("ui-select");
        this.setRectAttr(node);

        // this.cc.navTo(node.transform.x, node.transform.y);
      }
    },
    setRectAttr(node) {
      this.rectAttr = {
        ...node.transform,
        uid: node.uid,
        name: node.name,
      };
    },
    formatNum(num, fixed = 0) {
      return isNaN(num) ? fixed : parseFloat(num);
    },
    onCancelRect() {
      let currentNode = this.cc.datas.UIslectNode.selected;
      let idx = this.nodeList.findIndex((v) => v.uid === currentNode.uid);
      currentNode.transform = {
        ...currentNode.transform,
        x: this.formatNum(this.rectAttr.x),
        y: this.formatNum(this.rectAttr.y),
        w: this.formatNum(this.rectAttr.w),
        h: this.formatNum(this.rectAttr.h),
      };
      currentNode.name = this.rectAttr.name;

      this.cc.RenderManager.renderAll();
      if (idx !== -1) {
        let newObj = currentNode.toObj();

        if (this.bgData) {
          let data = this.bgData.getTexureData(currentNode.transform);
          newObj.src = data;
        }
        this.setRectAttr(newObj);
        this.saveNodeRo(newObj);
        this.nodeList.splice(idx, 1, newObj);
      }
    },
    onCommand(command) {
      this.command = command;
      this.cc.datas.currentCommand = command;
      switch (this.command) {
        case "created":
          this.oncreated().then((result) => {
            graph.saveProject({
              type: "image",

              projectId: this.projectId,
              src: result.src,
              key: "data/" + result.fileName,
              fileName: result.fileName,
            });
          });
          this.clearCommand();
          break;
        case "daochu":
                var a = document.getElementById("generate-file");
            if (!a) {
              a = document.createElement("a");
              a.id = "generate-file";
              a.hidden = true;
              document.body.append(a);
            }

            a.href = "/api/graph/project/export/zip/"+this.projectId;
            const newName = this.fileName.split(".");
            a.download = newName[0] + ".zip";
            a.dispatchEvent(
              new MouseEvent("click", { bubbles: false, cancelable: true })
            );
     
            this.onExport();
          break;
        case "origin":
          this.cc.navTo(0, 0);
          break;
      }
    },
    clearCommand() {
      this.command = "";
      this.cc.datas.currentCommand = "";
    },
    onExport() {
      let list = this.nodeList.map((v) => {
        return {
          key: v.name + ".png",
          frame: v.transform,
          offset: { x: 0, y: 0 },
          rotated: false,
          sourceColorRect: { x: 0, y: 0, w: v.transform.w, h: v.transform.h },
          sourceSize: { w: v.transform.w, h: v.transform.h },
        };
      });

      let textData = PlistReader.onGenerate(
        this.fileName,
        list,
        this.bgData.image
      );

      // var a = document.getElementById("generate-file");
      // if (!a) {
      //   a = document.createElement("a");
      //   a.id = "generate-file";
      //   a.hidden = true;
      //   document.body.append(a);
      // }

      // var file = new Blob([textData], { type: "text/plain" });
      // a.href = URL.createObjectURL(file);

      // const newName = this.fileName.split(".");

      // a.download = newName[0] + ".plist";
      // a.dispatchEvent(
      //   new MouseEvent("click", { bubbles: false, cancelable: true })
      // );
    },
    async oncreated(opt, render = true) {
      let result = null;
      let image = null;
      if (!opt) {
        result = await readFile();
        const formData = new FormData();

        formData.append("file", result.file);
        formData.append("key", "data");
        formData.append("fileName", result.fileName);
        if (result.file) {
          let data = await graph.uploadFile(formData);
          result.src = data.data.data;
        }
      } else {
        result = opt;
      }

      this.fileName = result.fileName;
      image = await dataURL2Image(result.data);

      let texture = this.cc.datas.renderDatas.find(
        (node) => node.name === "bg-1"
      );
      if (!texture) {
        texture = new TextTure({
          name: "bg-1",
          layer: "background",
          transform: { x: 0, y: 0 },
          image: image,
        });
      } else {
        texture.image = image;
      }

      this.bgData = texture;

      this.cc.datas.renderDatas.push(texture);

      if (render) {
        this.cc.RenderManager.renderAll();
      }

      return Promise.resolve(result);
    },
  },
};
</script>

<style lang="scss">
.u-editor {
  width: 100%;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  .toolbar {
    position: absolute;
    min-width: 240px;
    max-width: 372px;
    height: 64px;
    box-sizing: border-box;
    top: 20px;
    left: 20px;
    background-color: #fff;
    border-radius: 10px;
    z-index: 1000;
    display: flex;
    align-items: center;
    padding: 20px;
    padding-right: 0px;
    .tool-item {
      margin-right: 20px;
      .iconfont {
        font-size: 24px;
      }
      &.active {
        transform: scale(1.1);
        .iconfont {
          color: #409eff;
        }
      }
    }
    .tool-item:hover {
      transform: scale(1.1);
      .iconfont {
        color: #409eff;
      }
    }
  }
  .prop-panel {
    position: absolute;
    width: 320px;
    height: 640px;
    top: 104px;
    right: 20px;
    background-color: #e5e5e5;
    z-index: 1000;
    border-radius: 10px;
  }
  .img-panel {
    position: absolute;
    width: 372px;
    height: 640px;
    box-sizing: border-box;
    top: 104px;
    left: 20px;

    z-index: 1000;
    display: flex;
    .panel-left {
      width: 32px;

      // color: #000;
      background-color: #fff;
      border-radius: 10px 0 0 10px;
      box-sizing: border-box;
      position: absolute;
      top: 0;
      left: 0;
      overflow: hidden;
      .menu {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        height: 32px;

        padding: 10px;

        box-sizing: border-box;
        .iconfont {
          font-size: 14px;
        }
        &:hover {
          transform: scale(1.1);
          color: #409eff;
        }
        &.active {
          transform: scale(1.1);
          color: #409eff;
          background-color: #e5e5e5;
        }
      }
    }
    .panel-right {
      width: 100%;
      background-color: #e5e5e5;
      margin-left: 32px;
      border-radius: 0 10px 10px 10px;
      box-sizing: border-box;
      height: 100%;
      overflow: hidden;
      padding-left: 20px;
      .panel-header {
        box-sizing: border-box;
        display: flex;
        padding: 10px;
        align-items: center;
        .iconfont {
          font-size: 18px;
          padding: 5px;
          display: inline-block;
        }
      }

      .panel-right-warpped {
        height: 100%;

        overflow-y: auto;
      }
      .list-item {
        padding: 5px 0;
        margin-bottom: 5px;
        font-size: 0;
        display: flex;
        align-items: center;
      }
      .item-right {
        font-size: 14px;
        margin-left: 10px;
        color: #333;
        flex-grow: 1;
      }
      .item-opt {
        margin-right: 10px;
      }
    }
  }
}
.canvas-content {
  height: 100%;
  position: relative;
  .canvas-help {
    position: absolute;
    top: 0;
    left: 0;
  }
  .node-select {
    position: absolute;
    top: 0;
    left: 0;
    width: 46px;
    height: 46px;
    background-color: #0080002e;
  }
}
.c-canvas {
  // width: 100%;
  height: 100%;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
}
</style>